package com.zhaotianhao.controller;

import com.github.pagehelper.PageInfo;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.zhaotianhao.pojo.Brands;
import com.zhaotianhao.service.BrandsService;
import com.zhaotianhao.util.FileUtils;
import com.zhaotianhao.util.PDFUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author Z-7
 * @Date 2022/3/1
 */
@Controller
@RequestMapping("brands")
public class BrandsController {
    @DubboReference
    private BrandsService brandsService;
    @RequestMapping("list")
    public String to_list(@RequestParam(defaultValue = "1")int pageNum, @RequestParam(defaultValue = "3")int pageSize, Model model){
        PageInfo<Brands> page = brandsService.queryByPage(null, pageNum, pageSize);
        model.addAttribute("page",page);
        return "brands/brands_list";
    }
    @RequestMapping("getBrands")
    public @ResponseBody List<Brands> getBrands(){
        return brandsService.queryAll();
    }
    @RequestMapping("exportPDF")
    public void exportPDF(@RequestParam(defaultValue = "1")int pageNum,@RequestParam(defaultValue = "1")int mode ,HttpServletResponse response) throws Exception {
        PageInfo<Brands> brandsPageInfo = brandsService.queryByPage(null, pageNum, 3);
        // 生成文档对象
        Document document = new Document();
        // 生成的文件名称
        String fileName = UUID.randomUUID().toString() + ".pdf";
        // 生成pdf的路径
        PdfWriter pdfWriter = PDFUtils.createDoc(document, "d:/mypdf/" + fileName);
        // pdf生成的内容容器
        List<String> list = new ArrayList<>();
        // 容器中添加内容
        list.add("豪哥商城品牌列表");
        // pdf中添加内容     目标文档   实际内容  字体大小
        PDFUtils.addContent(document,list,18);
        // 添加表格
        PDFUtils.addTable(pdfWriter,new String[] {"编号","名称"},new String[] {"id","brandName"},brandsPageInfo.getList(),50,600);
        document.close();
        pdfWriter.close();
        // 添加图片水印
        PDFUtils.markImage("g:/img/321869.jpg",new FileInputStream("d:/mypdf/" + fileName),new FileOutputStream("d:/mypdf1/" + fileName),"版权所有");
        // 下载这个文件
        FileUtils.download(response,"d:/mypdf1/" + fileName, "品牌列表.pdf",mode);
    }
}
